package cn.stazxr.core;

import cn.stazxr.entity.YdlLoginUser;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

import static cn.stazxr.constants.RedisKeyConstant.TOKEN_PREFIX;
import static cn.stazxr.constants.RedisKeyConstant.TOKEN_TIME;

/**
 * @author talentestors
 * @version 1.0
 * @since 2025.10.30
 **/
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class TokenHandler {

	private final RedisTemplate redisTemplate;

	public Boolean authToken(String token, String userName) {
		if (token == null || token.isEmpty() || userName == null || userName.isEmpty()) {
			return Boolean.FALSE;
		}
		String tokenKey = getTokenPrefix(userName);
		YdlLoginUser user = redisTemplate.getObject(tokenKey + token, YdlLoginUser.class);
		if (user == null || !user.getToken().equals(token)) {
			return Boolean.FALSE;
		}
		return Boolean.TRUE;
	}

	public void saveToken(String token, YdlLoginUser loginUser) {
		String tokenPrefix = getTokenPrefix(loginUser.getYdlUser().getUserName());
		Set<String> keys = redisTemplate.keys(tokenPrefix + "*");
		redisTemplate.delete(keys.toArray(String[]::new));
		redisTemplate.setObject(tokenPrefix + token, TOKEN_TIME, loginUser);
	}

	public void resetToken(String token, String userName) {
		String tokenPrefix = getTokenPrefix(userName);
		redisTemplate.expire(tokenPrefix + token, TOKEN_TIME);
	}

	public void deleteToken(String token, String userName) {
		String tokenPrefix = getTokenPrefix(userName);
		redisTemplate.delete(tokenPrefix + token);
	}

	private static String getTokenPrefix(String userName) {
		return TOKEN_PREFIX + userName + ":";
	}

	public YdlLoginUser getYdlLoginUser(String token, String userName) {
		String tokenPrefix = getTokenPrefix(userName);
		return redisTemplate.getObject(tokenPrefix + token, YdlLoginUser.class);
	}
}
